package com.ctrip.ec.api.admin.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Created by cannon on 2018/3/26.
 */
public class JsonBodyExceptionResolver extends SimpleMappingExceptionResolver {

    private final static Logger logger = LoggerFactory.getLogger(JsonBodyExceptionResolver.class);

    public JsonBodyExceptionResolver() {
        this.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
                                              Object _handler, Exception ex) {

        HandlerMethod handler = (HandlerMethod) _handler;
        if (handler == null) {
            // like 'GET' not supported
            return null;
        }

        Method method = handler.getMethod();
        JsonBody meta = method.getAnnotation(JsonBody.class);
//
//        if (method.isAnnotationPresent(JsonBody.class)) {

        if (meta == null || meta.value() == true) {
            String config = super.determineViewName(ex, request);
            ResultBody body = null;

            boolean needLog = true;//验证类的就不要记日志了

            if(ex instanceof ValidateException){
                body = new ResultBody(ResponseStatus.VALIDATEERROR.getId(),ex.getMessage(),null,-1);
                needLog = false;
            }
            else if(ex instanceof UnauthorizedException){
                body= new ResultBody(ResponseStatus.Unauthorized.getId() ,ex.getMessage(),null);
            }
            else {
                body = new ResultBody(ResponseStatus.EXCEPTION.getId(), ex.toString(), null, -1);
            }
//            Object value = ex.toString();
            if(needLog){
                logger.error(ex.getMessage(),ex);
            }

            try {
                JsonSerializer.write(body, method, response);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // skip other resolver and view render
            return ModelAndViewResolver.UNRESOLVED;
        }

        return null;
    }

}
